let utils = require('../../utils/util.js')
let ImgLoader = require('../../utils/imgload.js')

// pages/detail/detail.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    header: {
      type: "detail",
      title: ""
    },
    lfIntro: {
      text: "",
      num: 0
    },
    host: utils.default.host,
    imghost: utils.default.imgHost,
    detailShow: false,
    lfList: [
    ],
    widthDisList: [],
    bMap: {
      "2": 30,
      "3": 15,
      "4": 11,
      "5": 8
    },
    lfGx: "",
    gxShow: false,
    rawData: {},
    pdId: '',
    isShow: false,
    descCurrent: 0,
    tipShow: true,
    showBigLf: false,
    imgLoader: null,
    imgList: [
      '../../img/fy_lingfu_bck_gq.png',
      '../../img/fy_lingfu_bck_jia.png',
      '../../img/fy_lingfu_default.png',
      // 'http://39.106.59.254/lfimg/kg_2.png',
      // 'http://39.106.59.254/lfimg/kg_1.png',
      // 'http://39.106.59.254/lfimg/kg_6.png',
      // 'http://39.106.59.254/lfimg/kg_3.png',
      // 'http://39.106.59.254/lfimg/kg_4.png',
      // 'http://39.106.59.254/lfimg/kg_5.png',
      // 'http://39.106.59.254/lfimg/fy_lingfu_spell_kai.png',
      // 'http://39.106.59.254/lfimg/fy_lingfu_spell_jia.png',
      // 'http://39.106.59.254/lfimg/fy_lingfu_highlight.png'
      'https://youdashen.com/augury-web/static/uploadImg/kg_2.png',
      'https://youdashen.com/augury-web/static/uploadImg/kg_1.png',
      'https://youdashen.com/augury-web/static/uploadImg/kg_6.png',
      'https://youdashen.com/augury-web/static/uploadImg/kg_3.png',
      'https://youdashen.com/augury-web/static/uploadImg/kg_4.png',
      'https://youdashen.com/augury-web/static/uploadImg/kg_5.png',
      'https://youdashen.com/augury-web/static/uploadImg/fy_lingfu_spell_kai.png',
      'https://youdashen.com/augury-web/static/uploadImg/fy_lingfu_spell_jia.png',
      'https://youdashen.com/augury-web/static/uploadImg/fy_lingfu_highlight.png'
    ],
    parentUrl: 'homepage'
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let self = this
    if (options.id) {
      self.setData({
        pdId: options.productId,
        id: options.orderCode ? result.orderCode : ''
      })
    } else {
      self.setData({
        pdId: options.productId
      })
    }
    // 判断是否是已购买符进入详情页
    if (parseInt(options.isBuy)) {
      // 获取用户已经购买的单个符的状态
      self.getBuyLfInfo(options.orderCode)
    } else {
      // 获取灵符信息
      self.getLfInfo(options.productId)
    }
    if (options.type) {
      console.log(options.type)
      self.setData({
        parentUrl: 'user'
      })
    }
    // self.getUserHistory()
    // 初始化图片加载
    self.imgLoader = new ImgLoader(self)
    self.data.imgList.forEach(item => {
      self.imgLoader.load(item)
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let self = this
    if (self.data.rawData.productVo){
      return {
        title: self.data.rawData.productVo.productAmuletPackageVo.name + ":" + self.data.rawData.productVo.productAmuletPackageVo.effect,
        path: '/pages/detail/detail?productId=' + self.data.pdId
      }
    } else {
      return {
        title: self.data.rawData.productAmuletPackageVo.name + ":" + self.data.rawData.productAmuletPackageVo.effect,
        path: '/pages/detail/detail?productId=' + self.data.pdId
      }
    }
  },

  // 关闭说明
  closeDesc: function () {
    let self = this
    self.setData({
      detailShow: false
    })
  },

  // 展开说明
  showDesc: function () {
    let self = this
    self.setData({
      descCurrent: 0,
      detailShow: true
    })
  },

  // 展开功效
  showGx: function () {
    let self = this
    self.setData({
      gxShow: true
    })
  },

  // 功效隐藏
  hideGx: function () {
    let self = this
    self.setData({
      gxShow: false
    })
  },

  // 返回
  backEvent: function () {
    let self = this
    if (self.data.parentUrl === 'homepage'){
      wx.switchTab({
        url: '../homepage/homepage'
      });
    }else{
      wx.switchTab({
        url: '../user/user'
      });
    }
    // wx.navigateBack()
  },

  // 获取符包信息
  getLfInfo: function (pdId) {
    let self = this
    wx.showLoading({
      title: '加载中',
    })
    wx.request({
      url: utils.default.host + '/api/product/getAmuletPackage.json?productId=' + pdId,
      success: function (res) {
        if (res.data.success) {
          wx.hideLoading()
          // 模拟状态，如果是订单查看的话也可以复用这个页面
          self.setData({
            "header.title": res.data.result.name,
            lfGx: res.data.result.productAmuletPackageVo.effect,
            "lfIntro.text": res.data.result.productAmuletPackageVo.illustrate,
            lfList: res.data.result.productAmuletPackageVo.productAmuletVoList,
            status: 0,
            lastStatus: 0,
            rawData: res.data.result,
            "lfIntro.num": res.data.result.showBuyCount
          })
          self.initLfWidth()
          console.log(self.data.lastStatus, 'lastStatus')
        }
      }
    })
  },

  // 获取已购符的状态
  getBuyLfInfo: function (orderId) {
    let self = this
    let thisApp = getApp()
    wx.showLoading({
      title: '加载中',
    })
    console.log('customerId', thisApp.globalData.userInfo.openId)
    wx.request({
      url: utils.default.host + '/api/customer/getCustomerProduct.json',
      method: 'GET',
      data: {
        versionId: utils.default.versionId,
        id: orderId,
        customerId: thisApp.globalData.userInfo.openId
      },
      success: function (res) {
        if (res.data.success) {
          wx.hideLoading()
          // 模拟状态，如果是订单查看的话也可以复用这个页面
          let status
          let lastStatus
          if (res.data.result.status === 'amuletPackagenormalBuy') {
            // 开光
            status = 1
            lastStatus = 1
          } else if (res.data.result.status === 'amuletPackageActivationBuy') {
            // 加持
            status = 2
            lastStatus = 2
            if (self.data.isBuy) {
              self.setData({
                isShow: true
              })
              setTimeout(function () {
                self.setData({
                  isShow: false
                })
              }, 8000)
            }
          } else if (res.data.result.status === 'amuletPackageStrengthenBuy') {
            // 加持完毕
            status = 4
            lastStatus = 2
            if (self.data.isBuy) {
              self.setData({
                isShow: true
              })
              setTimeout(function () {
                self.setData({
                  isShow: false
                })
              }, 8000)
            }
          } else if (res.data.result.status === 'amuletPackageOverdue') {
            // 过期
            status = 3
            if (res.data.result.lastStatus === 'amuletPackagenormalBuy'){
              lastStatus = 1
            } else {
              lastStatus = 2
            } 
          }
          console.log(lastStatus)
          // console.log(status, 'status')
          self.setData({
            "header.title": res.data.result.productVo.name,
            lfGx: res.data.result.productVo.productAmuletPackageVo.effect,
            "lfIntro.text": res.data.result.productVo.productAmuletPackageVo.illustrate,
            lfList: res.data.result.productVo.productAmuletPackageVo.productAmuletVoList,
            status: status,
            lastStatus: lastStatus,
            rawData: res.data.result,
            "lfIntro.num": res.data.result.productVo.showBuyCount ? res.data.result.productVo.showBuyCount : 0,
            widthDisList: [],
            id: orderId
          })
          if (self.data.widthDisList.length === 0) {
            self.initLfWidth()
          }
          console.log('test',self.data.id, res.data.result.status)
          self.getUserHistory(self.data.id, res.data.result.status)
        }
      }
    })
  },
  // 获取用户是否已阅开光、加持提示
  getUserHistory: function (orderCode, orderStatus) {
    let self = this
    let thisApp = getApp()
    console.log('getUserHistory')
    wx.request({
      // url: utils.default.host + '/api/user/getUserVisitHistory.json?versionId=' + utils.default.versionId + '&userId=' + thisApp.globalData.userInfo.openId + '&orderCode=' + self.data.orderCode + '&type=' + self.data.orderStatus,
      url: utils.default.host + '/api/user/getUserVisitHistory.json?versionId=' + utils.default.versionId + '&userId=' + thisApp.globalData.userInfo.openId + '&orderCode=' + orderCode + '&type=' + orderStatus,
      success: function (res) {
        console.log('get', res)
        if (res.data.success) {
          if (!res.data.result) {
            self.setData({
              tipShow: false
            })
          }
        }
      }
    })
  },
  setUserHistory: function () {
    let self = this
    let thisApp = getApp()
    wx.request({
      url: utils.default.host + '/api/user/setUserVisitHistory.json',
      method: 'POST',
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      data: {
        versionId: utils.default.versionId,
        userId: thisApp.globalData.userInfo.openId,
        orderCode: self.data.orderCode,
        type: self.data.orderStatus
      },
      success: function (res) {
        console.log('set', res)
        if (res.data.success) {
          if (!res.data.result) {
            self.setData({
              tipShow: false
            })
          }
        }
      }
    })
  },

  // 更新灵符的宽度
  initLfWidth: function () {
    let self = this
    let widthDisList = []
    wx.createSelectorQuery().selectAll('.lf-img').boundingClientRect(function (rects) {
      let firstWidth = rects[0].width
      // console.log(firstWidth, '#')
      rects.forEach(function (rect, index) {
        if (index === 0) {
          widthDisList.push(0)
        } else {
          let thisDis = firstWidth - rect.width
          // console.log(thisDis)
          widthDisList.push(thisDis)
        }
      })
      self.setData({
        widthDisList: widthDisList
      })
    }).exec()
  },

  // 第二次访问hack
  initLfSecWidth: function () {
    let self = this
    let widthDisList = []
    wx.createSelectorQuery().selectAll('.lf-img').boundingClientRect(function (rects) {
      let firstWidth = rects[0].width
      rects.forEach(function (rect, index) {
        if (index === 0) {
          widthDisList.push(0)
        } else {
          let thisDis = firstWidth - rect.width
          widthDisList.push(thisDis)
        }
      })
      self.setData({
        widthDisList: widthDisList
      })
    }).exec()
  },
  
  // 请符
  buyLf: function () {
    let thisApp = getApp()
    let self = this
    wx.getSystemInfo({
      success: function (res) {
        if (res.platform === "test") {
          wx.showModal({
            title: '提示',
            content: '受苹果政策影响，iOS暂未开放请符功能，请用户到安卓手机上请符。', 
          })
        } else {
          var prc = parseFloat(self.data.rawData.productAmuletPackageVo ? self.data.rawData.productAmuletPackageVo.price : self.data.rawData.productVo.productAmuletPackageVo.price)
          console.log(self.data.rawData.productAmuletPackageVo ? self.data.rawData.productAmuletPackageVo.price : self.data.rawData.productVo.productAmuletPackageVo.price)
          wx.showLoading({
            title: '请稍后',
          })
          wx.request({
            url: utils.default.host + '/api/order/submitOrder.json',
            method: 'POST',
            header: {
              "Content-Type": "application/x-www-form-urlencoded"
            },
            data: {
              customerId: thisApp.globalData.userInfo.openId,
              versionId: utils.default.versionId,
              productId: self.data.pdId,
              price: self.data.rawData.productAmuletPackageVo ? self.data.rawData.productAmuletPackageVo.price : self.data.rawData.productVo.productAmuletPackageVo.price,
              type: 'amuletPackagenormalBuy'
            },
            success: function (res) {
              if (res.data.success) {
                if (prc <= 0) {
                  wx.switchTab({
                    url: '../user/user'
                  });
                } else {
                  wx.hideLoading()
                  let payParams
                  let result = res.data.result
                  payParams = {
                    'lfName': self.data.rawData.name ? self.data.rawData.name : self.data.rawData.productVo.name,
                    'timeStamp': result.timeStamp,
                    'nonceStr': result.nonceStr,
                    'package': result.packageStr,
                    'signType': result.signType,
                    'paySign': result.paySign,
                    'orderCode': result.orderCode ? result.orderCode : '',
                    'orderVo': result.orderVo
                  }
                  wx.navigateTo({
                    url: '/pages/pay/pay?payParams=' + encodeURIComponent(JSON.stringify(payParams))
                  })
                }
              } else {
                wx.showToast({
                  title: '下单失败',
                  mask: true,
                  icon: 'none'
                })
              }
            }
          })
        }
      }
    })
    
  },

  // 开光提示
  kgLfTip: function () {
    let self = this
    self.setData({
      descCurrent: 3,
      detailShow: true
    })
    self.setUserHistory()
  },
  // 开光
  kgLf: function () {
    let thisApp = getApp()
    let self = this
    wx.getSystemInfo({
      success: function (res) {
        if (res.platform === "test") {
          wx.showModal({
            title: '提示',
            content: '受苹果政策影响，iOS暂未开放请符功能，请用户到安卓手机上请符。',
          })
        } else {
          var prc = parseFloat(self.data.rawData.productAmuletPackageVo ? self.data.rawData.productAmuletPackageVo.price : self.data.rawData.productVo.productAmuletPackageVo.price)
          wx.showLoading({
            title: '请稍后',
          })
          wx.request({
            url: utils.default.host + '/api/order/submitOrder.json',
            method: 'POST',
            header: {
              "Content-Type": "application/x-www-form-urlencoded"
            },
            data: {
              id: self.data.id,
              customerId: thisApp.globalData.userInfo.openId,
              versionId: utils.default.versionId,
              productId: self.data.pdId,
              price: self.data.rawData.productAmuletPackageVo ? self.data.rawData.productAmuletPackageVo.activationPrice : self.data.rawData.productVo.productAmuletPackageVo.activationPrice,
              type: 'amuletPackageActivationBuy'
            },
            success: function (res) {
              if (res.data.success) {
                if (prc <= 0) {
                  wx.switchTab({
                    url: '../user/user'
                  });
                } else {
                  wx.hideLoading()
                  let payParams
                  let result = res.data.result
                  payParams = {
                    'id': self.data.id,
                    'lfName': self.data.rawData.name ? self.data.rawData.name : self.data.rawData.productVo.name,
                    'timeStamp': result.timeStamp,
                    'nonceStr': result.nonceStr,
                    'package': result.packageStr,
                    'signType': result.signType,
                    'paySign': result.paySign,
                    'orderCode': result.orderCode ? result.orderCode : '',
                    'orderVo': result.orderVo
                  }
                  wx.navigateTo({
                    url: '/pages/pay/pay?payParams=' + encodeURIComponent(JSON.stringify(payParams))
                  })
                }
              } else {
                wx.showToast({
                  title: '下单失败',
                  mask: true,
                  icon: 'none'
                })
              }
            }
          })
        }
      }
    })
    
  },

  // 显示大灵符
  showBigImg: function (e) {
    let self = this
    wx.authorize({
      scope: 'scope.writePhotosAlbum',
      success: function (res) {
        console.log(res, '###')
        if (self.data.status !== 0) {
          self.setData({
            showBigLf: true
          })
          // 画到canvas上
          let ctx = wx.createContext();
          let sysInfo = wx.getSystemInfoSync()
          let width, height
          if (sysInfo.pixelRatio === 3 && sysInfo.windowWidth !== 375) {
            width = 320 * 1.1
            height = 518 * 1.1
          } else {
            width = 320
            height = 518
          }
          if (self.data.status === 1) {
            let index = e.currentTarget.dataset.index
            wx.showLoading({
              title: '加载中'
            })
            setTimeout(function () {
              ctx.drawImage('../../img/fy_lingfu_default.png', 0, 0, width, height)
              wx.downloadFile({
                url: self.data.imghost + self.data.lfList[index].amuletImageVoList[0].imageUrl,
                success: function (ires) {
                  ctx.drawImage(ires.tempFilePath, 0, 0, width, height)
                  wx.drawCanvas({
                    canvasId: "LfCanvas",
                    actions: ctx.getActions()
                  })
                  setTimeout(function () {
                    self.showBigImage()
                    self.setData({
                      showBigLf: false
                    })
                  }, 100)
                  wx.hideLoading()
                }, fail: function (fres) {
                  wx.getSetting({
                    success: function (res) {
                      if (!res.authSetting.scope.writePhotosAlbum) {
                        wx.showToast({
                          title: '请允许相册权限'
                        })
                      } else {
                        wx.showToast({
                          title: '获取灵符失败'
                        })
                      }
                    }
                  })

                }
              })
            }, 500)
          } else if (self.data.status === 2 || self.data.status === 4) {
            let index = e.currentTarget.dataset.index
            wx.showLoading({
              title: '加载中'
            })
            setTimeout(function () {
              ctx.drawImage('../../img/fy_lingfu_bck_jia.png', 0, 0, width, height)
              wx.downloadFile({
                url: self.data.imghost + self.data.lfList[index].amuletImageVoList[0].imageUrl,
                success: function (ires) {
                  ctx.drawImage(ires.tempFilePath, 0, 0, width, height)
                  wx.drawCanvas({
                    canvasId: "LfCanvas",
                    actions: ctx.getActions()
                  })
                  setTimeout(function () {
                    self.showBigImage()
                    self.setData({
                      showBigLf: false
                    })
                  }, 100)
                  wx.hideLoading()
                }, fail: function (fres) {
                  wx.showModal({
                    title: '',
                    content: JSON.stringify(fres),
                  })
                }
              })
            }, 500)
          } else if (self.data.status === 3) {
            let index = e.currentTarget.dataset.index
            wx.showLoading({
              title: '加载中'
            })
            setTimeout(function () {
              ctx.drawImage('../../img/fy_lingfu_bck_gq.png', 0, 0, width, height)
              wx.downloadFile({
                url: self.data.imghost + self.data.lfList[index].amuletImageVoList[0].imageUrl,
                success: function (ires) {
                  ctx.drawImage(ires.tempFilePath, 0, 0, width, height)
                  wx.drawCanvas({
                    canvasId: "LfCanvas",
                    actions: ctx.getActions()
                  })
                  setTimeout(function () {
                    self.showBigImage()
                    self.setData({
                      showBigLf: false
                    })
                  }, 100)
                  wx.hideLoading()
                }, fail: function (fres) {
                  wx.showToast({
                    title: '获取灵符失败'
                  })
                }
              })
            }, 500)
          }
        }
      },
      fail: function (res) {
        wx.showModal({
          title: '',
          content: '请允许保存到相册，否则将无法查看灵符及保存到手机',
          success: function (res) {
            if (res.confirm) {
              wx.openSetting({
                success: function (res) {
                  console.log(res)
                  if (!res.authSetting["scope.writePhotosAlbum"]) {
                    wx.showToast({
                      title: '请允许相册权限'
                    })
                  }
                }
              })
            }
          }
        })
      }
    })
  },
  
  hideBigImg: function () {
    let self = this
    self.setData({
      showBigLf: false
    })
  },

  // 下载灵符
  dlLf: function () {
    let sysInfo = wx.getSystemInfoSync()
    let width, height
    if (sysInfo.pixelRatio === 3 && sysInfo.windowWidth !== 375) {
      width = 320 * 1.5
      height = 518 * 1.5
    } else {
      width = 320
      height = 518
    }
    wx.canvasToTempFilePath({
      x: 0,
      y: 0,
      width: width,
      height: height,
      destWidth: 640,
      destHeight: 1036,
      canvasId: 'LfCanvas',
      success: function (res) {
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success: function (res2) {
            console.log(res2)
          }
        })
      }
    })
  },

  // 加持提示
  jcLfTip: function () {
    let self = this
    self.setData({
      descCurrent: 4,
      detailShow: true
    })
    self.setUserHistory()
  },
  
  // 加持灵符
  jcLf: function () {
    let thisApp = getApp()
    let self = this
    wx.getSystemInfo({
      success: function (res) {
        if (res.platform === "test") {
          wx.showModal({
            title: '提示',
            content: '受苹果政策影响，iOS暂未开放请符功能，请用户到安卓手机上请符。',
          })
        } else {
          var prc = parseFloat(self.data.rawData.productAmuletPackageVo ? self.data.rawData.productAmuletPackageVo.price : self.data.rawData.productVo.productAmuletPackageVo.price)
          wx.showLoading({
            title: '请稍后',
          })
          wx.request({
            url: utils.default.host + '/api/order/submitOrder.json',
            method: 'POST',
            header: {
              "Content-Type": "application/x-www-form-urlencoded"
            },
            data: {
              id: self.data.id,
              customerId: thisApp.globalData.userInfo.openId,
              versionId: utils.default.versionId,
              productId: self.data.pdId,
              price: self.data.rawData.productAmuletPackageVo ? self.data.rawData.productAmuletPackageVo.strengthenPrice : self.data.rawData.productVo.productAmuletPackageVo.strengthenPrice,
              type: 'amuletPackageStrengthenBuy'
            },
            success: function (res) {
              if (res.data.success) {
                if (prc <= 0) {
                  wx.switchTab({
                    url: '../user/user'
                  });
                } else {
                  wx.hideLoading()
                  let payParams
                  let result = res.data.result
                  payParams = {
                    'lfName': self.data.rawData.name ? self.data.rawData.name : self.data.rawData.productVo.name,
                    'timeStamp': result.timeStamp,
                    'nonceStr': result.nonceStr,
                    'package': result.packageStr,
                    'signType': result.signType,
                    'paySign': result.paySign,
                    'orderCode': result.orderCode ? result.orderCode : '',
                    'orderVo': result.orderVo
                  }
                  wx.navigateTo({
                    url: '/pages/pay/pay?payParams=' + encodeURIComponent(JSON.stringify(payParams))
                  })
                }
              } else {
                wx.showToast({
                  title: '下单失败',
                  mask: true,
                  icon: 'none'
                })
              }
            }
          })
        }
      }
    })
    
  },

  // 展示大符
  showBigImage: function (e) {
    let self = this
    let sysInfo = wx.getSystemInfoSync()
    let width, height
    if (sysInfo.pixelRatio === 3 && sysInfo.windowWidth !== 375) {
      width = 320 * 1.5
      height = 518 * 1.5
    } else {
      width = 320
      height = 518
    }
    wx.canvasToTempFilePath({
      x: 0,
      y: 0,
      width: width,
      height: height,
      destWidth: 640,
      destHeight: 1036,
      canvasId: 'LfCanvas',
      success: function (res) {
        wx.previewImage({
          urls: [res.tempFilePath],
        })
      }
    })
  }

})